<template>
  <div v-if="courseInfo !== {}">
    <navigationBar ref="navigationBar" :theme="navTheme"/>
    <videoPlayer
        ref="videoPlayer"
        v-model="showVideoPlayer"
        :vid="videoPlayerConfig.vid"
        :auth="videoPlayerConfig.playauth"
        @close="showVideoPlayer = false"/>
    <div class="course-detail-container">
      <div class="course-header">
        <div class="content-container">
          <div class="breadcrumbs-row">
            <v-breadcrumbs
                :items="courseCategoryInfo"
                :large="windowWidth > 900"/>
            <v-btn
                text
                plain
                @click="changeCollectionStatus"
                :ripple="false"
                v-show="!isCollected">
              <v-icon
                  :size="windowWidth > 900 ? 16 : 15">
                far fa-star
              </v-icon>
              <span>收藏课程</span>
            </v-btn>
            <v-btn
                text
                plain
                @click="changeCollectionStatus"
                :ripple="false"
                v-show="isCollected">
              <v-icon
                  color="#fb8c00"
                  :size="windowWidth > 900 ? 16 : 15">
                fas fa-star
              </v-icon>
              <span class="orange--text text--darken-1">取消收藏</span>
            </v-btn>
          </div>
          <div class="course-title">
            {{ courseInfo.hasOwnProperty('courseBase') ? courseInfo.courseBase.name.toUpperCase() : '' }}
          </div>
          <div class="course-desc">
            {{ courseInfo.courseBase.description }}
          </div>
          <div class="course-basic-info">
            <div class="item">
              {{ courseInfo.courseBase.buyCount | formatBuyCount }}
            </div>
            <div class="item">
              {{ courseInfo.courseBase.grade | formatGrade }}课程
            </div>
            <div class="item">
              {{ courseInfo.courseBase.users| formatSuitableUsers }}
            </div>
          </div>
          <div class="course-join">
            <v-btn
                @click="toLearner"
                class="btn__join"
                color="primary"
                :large="windowWidth <= 1500 && windowWidth > 700"
                :x-large="windowWidth > 1500"
                :width="windowWidth > 1500 ? 150 : 120"
                rounded
                depressed>
              立即参加
            </v-btn>
            <div class="price">
              <div class="price__current">
                {{ courseInfo.courseMarket.price | formatPrice }}
              </div>
              <div class="price__original" v-if="courseInfo.courseMarket.price_old">
                {{ courseInfo.courseMarket.price_old | formatPrice }}
              </div>
            </div>
          </div>
        </div>
        <v-hover v-slot="{ hover }">
          <div class="img-container" @click="handleVideoClick">
            <v-img
                src="https://pic4.zhimg.com/v2-13ee1f2e14d10b8686f91bea4c03bf77_r.jpg"
                height="inherit"
                max-height="800px">
              <template v-slot:default>
                <v-hover v-slot="{ hover }">
                  <div
                      class="img-wrapper"
                      :class="hover || windowWidth < 700 ? 'img-wrapper__hover' : ''">
                    <v-btn text fab x-large>
                      <v-icon
                          :color="hover ? 'rgba(255, 255, 255, 1)' : 'rgba(255, 255, 255, .75)'"
                          :size="windowWidth > 1200 ? 48 : 42">
                        fas fa-play
                      </v-icon>
                    </v-btn>
                  </div>
                </v-hover>
              </template>
            </v-img>
          </div>
        </v-hover>
      </div>
      <div class="course-body">
        <div class="course-key-info">
          <div class="item teacher">
            <v-avatar v-if="windowWidth > 700" @click="gotoTeacherDetail(courseInfo.teacher.id)">
              <v-img :src="courseInfo.teacher.avatar">
                <template v-slot:placeholder>
                  <v-icon>
                    fas fa-user-graduate
                  </v-icon>
                </template>
              </v-img>
            </v-avatar>
            <v-avatar v-else>
              <v-icon>
                fas fa-user-graduate
              </v-icon>
            </v-avatar>
            <div class="item-text text-no-wrap">
              <span class="item-title">
                主讲教师
              </span>
              <span class="item-content" @click="gotoTeacherDetail(courseInfo.teacher.id)">
                {{ courseInfo.teacher.name }}
              </span>
            </div>
          </div>
          <v-divider vertical/>
          <div class="item">
            <v-avatar>
              <v-icon>
                fas fa-calendar-alt
              </v-icon>
            </v-avatar>
            <div class="item-text text-no-wrap">
              <span class="item-title">
                课程时长
              </span>
              <span class="item-content">
                {{ courseInfo.courseBase.lessonNum }} 次课
              </span>
            </div>
          </div>
          <v-divider vertical/>
          <div class="item">
            <v-avatar>
              <v-icon>
                fas fa-book-open
              </v-icon>
            </v-avatar>
            <div class="item-text">
              <span class="item-title text-no-wrap">
                学习模式
              </span>
              <span class="item-content">
                {{ courseInfo.courseBase.studymodel | formatLearnMode }}
              </span>
            </div>
          </div>
          <v-divider vertical/>
          <div class="item">
            <v-avatar>
              <v-icon>
                fas fa-book
              </v-icon>
            </v-avatar>
            <div class="item-text">
              <span class="item-title text-no-wrap">
                先修课程
              </span>
              <v-tooltip bottom v-if="windowWidth <= 1000">
                <template v-slot:activator="{ on, attrs }">
                  <span
                      class="item-content text-no-wrap text-truncate"
                      style="cursor: pointer"
                      v-bind="attrs"
                      v-on="on">
                    {{ courseInfo.courseBase.ap }}
                  </span>
                </template>
                <span>{{ courseInfo.courseBase.ap }}</span>
              </v-tooltip>
              <span
                  class="item-content text-no-wrap text-truncate"
                  v-else>
                {{ courseInfo.courseBase.ap }}
              </span>
            </div>
          </div>
        </div>
        <div class="course-detail-info">
          <div class="detail-info__left">
            <div
                class="detail-container mb-10"
                ref="courseDetail0"
                id="courseDetail0"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-th-large
                </v-icon>
                <span>课程介绍</span>
              </div>
              <div class="detail-content">
                <div class="basic-introduction pa-7 mt-2 mb-6">
                  <span class="text-justify text-body-2">
                    {{ courseInfo.courseDetail.description }}
                  </span>
                </div>
                <p class="text-justify text-body-2">
                  {{ courseInfo.courseDetail.overview }}
                </p>
              </div>
            </div>
            <div
                class="detail-container mb-10"
                ref="courseDetail1"
                id="courseDetail1"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-graduation-cap
                </v-icon>
                <span>课程目标</span>
              </div>
              <div class="detail-content">
                <p class="text-justify text-body-2">
                  {{ courseInfo.courseDetail.target }}
                </p>
              </div>
            </div>
            <div
                class="detail-container mb-10"
                ref="courseDetail2"
                id="courseDetail2"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-bookmark
                </v-icon>
                <span>课程内容</span>
              </div>
              <div class="detail-content">
                <v-treeview
                    :items="coursePlanNode"
                    expand-icon="mdi-chevron-down"
                    dence
                    open-all
                    transition
                    hoverable/>
              </div>
            </div>
            <div
                class="detail-container mb-10"
                ref="courseDetail3"
                id="courseDetail3"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-user-graduate
                </v-icon>
                <span>授课讲师</span>
              </div>
              <div class="detail-content mt-2">
                <div class="teacher">
                  <v-avatar size="120" @click="gotoTeacherDetail(courseInfo.teacher.id)">
                    <v-img :src="courseInfo.teacher.avatar">
                      <template v-slot:placeholder>
                        <v-icon>
                          fas fa-user-graduate
                        </v-icon>
                      </template>
                    </v-img>
                  </v-avatar>
                  <div class="teacher-introduction">
                    <p class="name" @click="gotoTeacherDetail(courseInfo.teacher.id)">{{
                        courseInfo.teacher.name
                      }}老师</p>
                    <p class="intro">{{ courseInfo.teacher.intro }}</p>
                    <p class="career">{{ courseInfo.teacher.career }}</p>
                  </div>
                </div>
              </div>
            </div>
            <div
                class="detail-container mb-10"
                ref="courseDetail4"
                id="courseDetail4"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-check-square
                </v-icon>
                <span>先修课程</span>
              </div>
              <div class="detail-content">
                <p class="text-justify text-body-2">
                  {{ courseInfo.courseDetail.ap }}
                </p>
              </div>
            </div>
            <div
                class="detail-container mb-10"
                ref="courseDetail5"
                id="courseDetail5"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-bell
                </v-icon>
                <span>课程说明</span>
              </div>
              <div class="detail-content">
                <p class="text-justify text-body-2">
                  {{ courseInfo.courseDetail.problem }}
                </p>
              </div>
            </div>
            <div
                class="detail-container mb-10"
                ref="courseDetail6"
                id="courseDetail6"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-box
                </v-icon>
                <span>相关资源</span>
              </div>
              <div class="detail-content">
                <p class="text-justify text-body-2">
                  {{ courseInfo.courseDetail.resources }}
                </p>
              </div>
            </div>
            <div
                class="detail-container more-courses mb-10"
                ref="courseDetail7"
                id="courseDetail7"
                v-intersect="{
                handler: onIntersect,
                options: {
                  threshold: [0.5]
                }
              }">
              <div class="detail-title">
                <v-icon color="primary">
                  fas fa-book
                </v-icon>
                <span>推荐课程</span>
              </div>
              <div class="detail-content course-card-container justify-space-between">
                <div
                    class="course-card my-2"
                    v-for="course in teacherCoursesList"
                    :key="course.id"
                    v-ripple>
                  <v-img
                      :src="course.pic"></v-img>
                  <div class="course-info">
                    <div>
                      <p class="course-title">{{ course.name }}</p>
                      <p class="course-teacher">{{ courseInfo.teacher.name }}</p>
                      <p class="course-category">{{ course.st | formatCourseCategory }}</p>
                    </div>
                    <div class="course-price">
                      <p class="price__current">
                        {{ course.price | formatPrice }}
                      </p>
                      <p class="price__original" v-if="course.price_old">
                        {{ course.price_old | formatPrice }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="detail-info__right pt-4">
            <catalog
                ref="catalog"
                v-model="catalogList"
                :fixed="catalogFixed"
                @catalogClick="handleCatalogClick"/>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import navigationBar from "@/components/navigationBar/navigationBar";
import videoPlayer from "@/components/videoPlayer/videoPlayer";
import {formatCourseCategory} from "@/common/js/utils";
import {
  addCourseToCollection,
  getCourseAllInfo,
  getCourseCollectionStatus,
  getCourseVideoInfo,
  getVideoAuth,
  removeCourseInCollection
} from "../../api";
import catalog from "@/components/catalog/catalog";
import {getCourseListByTeacherId} from "../../api";

export default {
  name: "courseDetail",
  components: {
    navigationBar, videoPlayer, catalog
  },
  data() {
    return {
      courseId: '', //课程ID
      courseInfo: {}, //课程信息
      courseCategoryInfo: [], //课程分类信息列表（用于面包屑导航）
      teacherCoursesList: [], //讲师的更多课程列表
      catalogList: [
        {
          id: 'courseDetail0',
          title: '课程介绍',
        },
        {
          id: 'courseDetail1',
          title: '课程目标'
        },
        {
          id: 'courseDetail2',
          title: '课程内容'
        },
        {
          id: 'courseDetail3',
          title: '授课讲师'
        },
        {
          id: 'courseDetail4',
          title: '先修课程'
        },
        {
          id: 'courseDetail5',
          title: '课程说明'
        },
        {
          id: 'courseDetail6',
          title: '相关资源'
        },
        {
          id: 'courseDetail7',
          title: '推荐课程'
        },
      ], //目录列表
      catalogFixed: false, //目录是否为固定位置显示
      catalogOffsetTop: 0, //目录在初始位置时距离页面顶部的高度
      isCollected: false, //用户是否已经收藏当前课程
      showVideoPlayer: false, //是否显示视频播放器弹出窗
      videoPlayerConfig: {}, //视频播放器配置
    }
  },
  methods: {
    // 初始化
    async init() {
      this.courseId = this.$route.params.courseId ?? '';
      // this.courseInfo = courseInfo
      await this.getCourseInfo();
      this.catalogOffsetTop = this.$refs.catalog.$refs.catalog.offsetTop; //获取目录的初始位置
      // this.teacherCoursesList = teacherCourses;
      const category = formatCourseCategory(this.courseInfo.courseBase.st);
      this.courseCategoryInfo = [
        {
          text: category.mt,
          href: '/',
        },
        {
          text: category.st,
          href: '/',
        }
      ];
    },
    // 获取课程信息
    async getCourseInfo() {
      const getCourseInfoPromise = new Promise((resolve, reject) => {
        getCourseAllInfo(this.courseId).then(res => {
          this.courseInfo = res.data
          this.videoPlayerConfig.vid = this.courseInfo.courseDetail.introduceVideo
          resolve(res);
        }).catch(err => {
          console.error(err);
          reject(err);
        });
      })
      const getCourseCollectionStatusPromise = new Promise((resolve, reject) => {
        getCourseCollectionStatus(this.courseId).then(res => {
          resolve(res);
        }).catch(err => {
          console.error(err);
          reject(err);
        });
      })

      await Promise.all([getCourseInfoPromise, getCourseCollectionStatusPromise]);

      getCourseListByTeacherId(1, 4, this.courseInfo.teacher.id).then(res => {
        this.teacherCoursesList = res.data;
      })
    },
    // 视频预览点击事件
    handleVideoClick() {
      if (this.showVideoPlayer) {
        this.showVideoPlayer = false;
      }
      this.showVideoPlayer = true;
      if (!!this.videoPlayerConfig.vid) {
        getVideoAuth(this.videoPlayerConfig.vid).then(res => {
          if (!!res.data) {
            this.videoPlayerConfig = {
              vid: this.videoPlayerConfig.vid,
              playauth: res.data
            };
            this.$refs.videoPlayer.config = {
              vid: this.videoPlayerConfig.vid,
              playauth: res.data
            }
          }
        }).catch(err => {
          console.error(err);
        });
      } else {
        getCourseVideoInfo(this.courseId).then(res => {
          if (!!res.videoSourceId) {
            const vid = res.videoSourceId;
            getVideoAuth(vid).then(res => {
              if (!!res.data.playAuth) {
                this.videoPlayerConfig = {
                  vid: vid,
                  playauth: res.data.playAuth
                };
              }
            }).catch(err => {
              console.error(err);
            });
          } else {
            console.log('无视频信息');
          }
        }).catch(err => {
          console.error(err)
        });
      }
    },
    toLearner() {
      this.$router.push(
          {
            path:"/learner/"+this.courseId
          }
      )
    },
    /**
     * 目录点击事件
     * @param {String} id 目录节点的序号
     */
    handleCatalogClick(id) {
      this.$vuetify.goTo(this.$refs[id], {
        duration: 500
      });
    },
    // 节点视界发生交互时的回调方法（元素是否可见）
    onIntersect(entries, observer, isIntersecting) {
      this.$refs.catalog.onIntersect(entries[0].target.id, isIntersecting);
    },
    /**
     * 跳转教师详情页
     * @param {String} teacherId 教师ID
     */
    gotoTeacherDetail(teacherId) {
      this.$router.push(`/teacher/${teacherId}`);
    },
    // 改变课程收藏状态
    async changeCollectionStatus() {
      if (this.isCollected) {
        this.isCollected = false;
        // await removeCourseInCollection(this.courseId).then(res => {
        //     console.log(res);
        // }).catch(err => {
        //     console.error(err);
        // });
      } else {
        this.isCollected = true;
        // await addCourseToCollection(this.courseId).then(res => {
        //     console.log(res);
        // }).catch(err => {
        //     console.error(err);
        // });
      }
    },
  }
  ,
  computed: {
    // 屏幕宽度实时数值
    windowWidth() {
      return this.$store.state.screenWidth + 5;
    }
    ,
    // 页面滚动高度
    scrollTop() {
      return this.$store.state.scrollTop;
    }
    ,
    // 导航栏主题
    navTheme() {
      return this.windowWidth > 700 ? 'light' : 'transparent';
    }
    ,
    // 修改课程计划数据以匹配v-tree组件
    coursePlanNode: {
      get() {
        let coursePlanNode = this.courseInfo.coursePlanNode.children;
        coursePlanNode.forEach(node => {
          if (node.pname) {
            node.name = node.pname;
          }
          if (node.children) {
            node.children.forEach(child => {
              if (child.pname) {
                child.name = child.pname;
              }
            })
          }
        });
        return coursePlanNode;
      }
    }
  }
  ,
  filters: {
    // 格式化购买数量
    formatBuyCount(buyCount) {
      return `已有 ${buyCount} 人参加`;
    }
    ,
    // 格式化面向用户
    formatSuitableUsers(users) {
      return `面向${users}`;
    }
    ,
    /**
     * 格式化课程分类
     * @param {String} st 课程小分类ID
     * @return {String} 格式化后的课程分类文字
     */
    formatCourseCategory(st) {
      const category = formatCourseCategory(st);
      return `${category.mt} / ${category.st}`;
    }
  }
  ,
  watch: {
    windowWidth: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.catalogFixed = false;
          this.catalogOffsetTop = this.$refs.catalog.$refs.catalog.offsetTop;
        });
      }
    }
    ,
    scrollTop(nval) {
      this.catalogFixed = nval >= this.catalogOffsetTop - 30; //页面滚动高度小于目录初始位置时让目录归位
    }
    ,
  }
  ,
  mounted() {
    this.$nextTick(() => {
      // this.catalogOffsetTop = this.$refs.catalog.$refs.catalog.offsetTop; //获取目录的初始位置
    });
  }
  ,
  created() {
    this.init();
  }
}
</script>

<style lang="scss" scoped>
@import "courseDetail";
</style>